/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.opgea.crm.web.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.opgea.crm.common.SetupsAttributeQualifier;
import com.opgea.crm.common.SetupsModuleQualifier;
import com.opgea.crm.common.constant.ApplicationConstant;
import com.opgea.crm.common.constant.ApplicationConstant.ActiveQualifier;
import com.opgea.crm.common.util.DateUtil;
import com.opgea.crm.domain.entities.Activity;
import com.opgea.crm.domain.entities.AdditionalContact;
import com.opgea.crm.domain.entities.Company;
import com.opgea.crm.domain.entities.Companyaddresses;
import com.opgea.crm.domain.entities.Companycompetitors;
import com.opgea.crm.domain.entities.Employee;
import com.opgea.crm.domain.entities.Lead;
import com.opgea.crm.domain.entities.Leademails;
import com.opgea.crm.domain.entities.Leadphones;
import com.opgea.crm.domain.entities.Leadprofile;
import com.opgea.crm.domain.entities.Opportunity;
import com.opgea.crm.domain.entities.SetupsValue;
import com.opgea.crm.domain.modal.JsonModelMap;
import com.opgea.crm.services.ActivityService;
import com.opgea.crm.services.AdditionalContactService;
import com.opgea.crm.services.EmployeeService;
import com.opgea.crm.services.LeadService;
import com.opgea.crm.services.OpportunityService;
import com.opgea.crm.services.QualifierService;
import com.opgea.crm.services.SetupService;
import com.opgea.crm.services.security.CrmUserServiceImpl;
import com.opgea.crm.web.form.DynamicActivityForm;
import com.opgea.crm.web.form.DynamicContactForm;
import com.opgea.crm.web.form.LeadForm;
import com.opgea.crm.web.form.LeadOppForm;
import com.opgea.crm.web.modal.LoggedUser;

/**
 *
 * @author User1
 */
@Controller
@RequestMapping(value="lead")
public class LeadController {


	Logger logger=Logger.getLogger(LeadController.class);
	@Autowired
	LeadService leadService;
	@Autowired
        OpportunityService opportunityService;
	@Autowired
	SetupService setupService;
	@Autowired
	EmployeeService employeeService;
	@Autowired
	ActivityService activityService;
	@Autowired
	AdditionalContactService contactService;
	@Autowired
	QualifierService qualifierService;
	@Autowired
	CrmUserServiceImpl userService;
	
	@RequestMapping(method=RequestMethod.GET)
	public String show(HttpServletRequest request){
		return "lead";
	}
	
	@RequestMapping(method = RequestMethod.GET, value="showLeadDetails")
	public @ResponseBody
	Map<String, Object> showLeadDetails(@RequestParam("leadId")String leadId){
		Lead lead = leadService.findLead(new Long(leadId));
		logger.debug("Lead : >>> "+lead);
		return JsonModelMap.success().data(new LeadForm(lead));
	}
	
	@RequestMapping(method = RequestMethod.GET, value="showContactDetailsInPopup")
	public @ResponseBody
	Map<String, Object> showContactDetailsInPopup(@RequestParam("contactId")String contactId){
		AdditionalContact contact = contactService.find(new Long(contactId));
		logger.info("Lead : >>> "+contact);
		logger.debug("Lead : >>> "+contact);
		return JsonModelMap.success().data(new DynamicContactForm(contact));
	}
	
    @RequestMapping(value="save", method=RequestMethod.POST)
    public 
    @ResponseBody Map<String, Object> save(@RequestParam(required=true, value="action") String action,
    									   @RequestBody LeadForm form,
    									   HttpServletRequest request){
    	
    	logger.debug("Lead Controller >> save >> Inside Method");
    	Lead lead = null;
    	Company company = null;
    	Leademails email = null;
    	Leadprofile leadProfile = null;
    	Leadphones phone1 = null;
    	Leadphones phone2 = null;
    	Leadphones phone3 = null;
    	Leadphones phone4 = null;
    	Companyaddresses companyAddress = null;
    	Companycompetitors competitor1 = null;
    	Companycompetitors competitor2 = null;
    	Companycompetitors competitor3 = null;
    	Employee owner = null; 
    	
    	if(action.equalsIgnoreCase("save")){
    		lead = new Lead();
    		company = new Company();
    		email = new Leademails();
    		leadProfile =  new Leadprofile();
    		companyAddress = new Companyaddresses();
    		owner = employeeService.find(form.getOwnerId());
    		leadProfile.setEmployee(owner);
        	
    		phone1 = new Leadphones();
    		phone2 = new Leadphones();
    		phone3 = new Leadphones();
    		phone4 = new Leadphones();
    		
    		competitor1 = new Companycompetitors();
    		competitor2 = new Companycompetitors();
    		competitor3 = new Companycompetitors();
    	}
    	if(action.equalsIgnoreCase("update")){
    		lead = leadService.findLead(new Long(form.getLeadId()));
    		company = lead.getCompany();
    		email = lead.getLeademail();
    		leadProfile = lead.getLeadprofile();
    		owner = leadProfile.getEmployee();
    		leadProfile.setEmployee(owner);
    		
    		List<Leadphones> phones = 
    			new ArrayList<Leadphones>(lead.getLeadphonesCollection());
    		List<Companyaddresses> addresses = 
    			new ArrayList<Companyaddresses>(company.getCompanyaddressesCollection());
    		List<Companycompetitors> competitors = 
    			new ArrayList<Companycompetitors>(company.getCompanycompetitorsCollection());
    		
    		
    		if(phones.get(0)!=null){
    			phone1 = phones.get(0);
    		}
    		if(phones.get(1)!=null){
    			phone2 = phones.get(1);
    		}
    		if(phones.get(2)!=null){
    			phone3 = phones.get(2);
    		}
    		if(phones.get(3)!=null){
    			phone4 = phones.get(3);
    		}
    		if(addresses.get(0)!=null){
    			companyAddress = addresses.get(0);
    		}
    		
    		if(competitors.get(0)!=null){
    			competitor1 = competitors.get(0);
    		}
    		if(competitors.get(1)!=null){
    			competitor2 = competitors.get(1);
    		}
    		if(competitors.get(2)!=null){
    			competitor3 = competitors.get(2);
    		}
    	}
    	
    	//lead email
    	email.setEmailQualifier(ApplicationConstant.EmailQualifier.Primary.ordinal());
    	email.setAddress(form.getEmail());
    	email.setLead(lead);
    	
    	//lead phone
    	phone1.setPhoneQualifier(ApplicationConstant.PhoneQualifier.Work.ordinal());
    	phone1.setPhoneNo(form.getPhone1());
    	phone1.setLead(lead);
    	
    	phone2.setPhoneQualifier(ApplicationConstant.PhoneQualifier.Mobile.ordinal());
    	phone2.setPhoneNo(form.getPhone2());
    	phone2.setLead(lead);
    	
    	phone3.setPhoneQualifier(ApplicationConstant.PhoneQualifier.Home.ordinal());
    	phone3.setPhoneNo(form.getPhone3());
    	phone3.setLead(lead);
    	
    	phone4.setPhoneQualifier(ApplicationConstant.PhoneQualifier.Fax.ordinal());
    	phone4.setPhoneNo(form.getPhone4());
    	phone4.setLead(lead);
    	List<Leadphones> leadPhones = new ArrayList<Leadphones>();
    	
    	leadPhones.add(phone1);
    	leadPhones.add(phone2);
    	leadPhones.add(phone3);
    	leadPhones.add(phone4);
    	
    	//lead profile
    	leadProfile.setLead(lead);
    	leadProfile.setSource(setupService.findById(form.getSourceId()));
    	leadProfile.setAction(setupService.findById(form.getActionId()));
    	leadProfile.setCategory(setupService.findById(form.getCategoryId()));
    	leadProfile.setClosingProbability(setupService.findById(form.getClosingProbabilityId()));
    	leadProfile.setGrade(setupService.findById(form.getGradeId()));
    	leadProfile.setStage(setupService.findById(form.getLeadStageId()));
    	
    	//sales person
    	leadProfile.setEmployee(employeeService.find(form.getOwnerId()));
    	leadProfile.setNotes(form.getNotes().getBytes());
    	leadProfile.setLead(lead);
    	
    	//company address
    	companyAddress.setAddressQualifier(ApplicationConstant.AddressQualifier.Business.ordinal());
    	companyAddress.setStreet1(form.getStreet1());
    	companyAddress.setStreet2(form.getStreet2());
    	companyAddress.setCountry(form.getCountry());
    	companyAddress.setCity(form.getCity());
    	List<Companyaddresses> companyAddresses = new ArrayList<Companyaddresses>();
    	companyAddresses.add(companyAddress);
    	
    	//company
    	company.setName(form.getCompanyName());
    	company.setWebsite(form.getWeb());
    	company.setIndustryType(setupService.findById(form.getIndustryTypeId()));
    	company.setCompanySize(new Integer(form.getCompanySize()));
    	company.setAnnualRevenue(new Long(form.getAnnualRevenue()));
    	company.setCompanyaddressesCollection(companyAddresses);    	
    	companyAddress.setCompany(company);
    	

    	//company competitor
    	competitor1.setName(form.getCompetitor1());
    	competitor1.setNotes("testnotes");
    	competitor1.setCompany(company);
    	competitor2.setName(form.getCompetitor2());
    	competitor2.setNotes("testnotes");
    	competitor2.setCompany(company);
    	competitor3.setName(form.getCompetitor3());
    	competitor3.setNotes("testnotes");
    	competitor3.setCompany(company);
    	List<Companycompetitors> companyCompetitors = new ArrayList<Companycompetitors>();
    	companyCompetitors.add(competitor1);
    	companyCompetitors.add(competitor2);
    	companyCompetitors.add(competitor3);
    	company.setCompanycompetitorsCollection(companyCompetitors);
    	
    	lead.setId(new Long(form.getLeadId()));
    	lead.setFirstName(form.getFirstName());
    	lead.setMiddleInitial(form.getMiddleInitial());
    	lead.setLastName(form.getLastName());
    	lead.setTitle(form.getTitle());
    	lead.setCompany(company);
    	lead.setLeademail(email);
    	lead.setLeadphonesCollection(leadPhones);
    	lead.setLeadprofile(leadProfile);
    	lead.setLeadStatus(form.getLeadStatusType());

    	logger.debug("Lead Controller >> save >> Before Save!");
    	if(action.equalsIgnoreCase("save")){
        	lead.setCreatedBy(LoggedUser.getUser(request));
        	lead.setCreatedAt(new Date());
        	if(LoggedUser.getUser(request) != null){
        		leadService.createLead(lead);
        	}else{
        		return JsonModelMap.success().data("Your Session Expired. <br> You need to relogin.");		
        	}
    	}
    	if(action.equalsIgnoreCase("update")){
    		leadService.update(lead);
    	}

    	Map<String, Object> successMap = new HashMap<String, Object>();
		successMap.put("success", "A new lead added successfully!");
		return JsonModelMap.success().data(lead.getId());
    	//return successMap;
    }
    
	@RequestMapping(method = RequestMethod.POST, value = "saveActivity")
	public @ResponseBody
	Map<String, Object> saveActivity(@RequestBody DynamicActivityForm form,
				@RequestParam(required=true, value="action")String action, HttpServletRequest request) {
		
			System.out.println("LEAD >> saveACTIVITY >> InsideMethod "+action);
			
			Activity activity = null;
			Opportunity opportunity = null;
			Lead lead = null;
			Employee assignedTo = null;
			
			if(action.equalsIgnoreCase("save")){
				activity = new Activity();
				opportunity = opportunityService.find(new Long(form.getOpportunityId()));
				lead = leadService.findLead(new Long(form.getActivityLeadId()));
				assignedTo = employeeService.find(new Long(form.getAssignedToId()));
			}
			
			if(action.equalsIgnoreCase("update")){
				activity = activityService.find(form.getActivityId());
				opportunity = opportunityService.find(new Long(form.getOpportunityId()));
				lead = activity.getLead();
				System.out.println("Controller: Dynamic Activity Form :"+form);
				assignedTo = employeeService.find(form.getAssignedToId());
				}
			activity.setAssignTo(assignedTo);			
			activity.setActivityType(setupService.findById(form.getActivityTypeId()));
			activity.setActivityStage(setupService.findById(form.getActivityStageId()));
			activity.setActivityStatus(setupService.findById(form.getStatusId()));
			activity.setPriority(setupService.findById(form.getPriorityId()));
			
			activity.setScheduledDate(DateUtil.stringToDate(form.getDueDate()));
			activity.setDuration(new Integer(form.getDuration()));
			activity.setReminderDate(DateUtil.stringToDate(form.getReminderDate()));
			
			activity.setNote(form.getActivityNotes());
			activity.setSubject(form.getSubject());
			activity.setLead(lead);
			activity.setOpportunity(opportunity);
			
			
			if(action.equalsIgnoreCase("save")){
				activity.setCreatedBy(LoggedUser.getUser(request));
				activity.setCreatedAt(new Date());
				activityService.create(activity);
			}
			if(action.equalsIgnoreCase("update")){
				activityService.update(activity);
			}
			
		return JsonModelMap.success().data(activity.getId());
	}    

	@RequestMapping(method = RequestMethod.POST, value = "saveContact")
	public @ResponseBody
	Map<String, Object> saveContact(
				@RequestBody DynamicContactForm form,
				@RequestParam(required=true, value="action")String action,
				@RequestParam(required=true, value="leadId")String leadId,
				@RequestParam(required=true, value="contactId")String contactId,
				HttpServletRequest request) {
			logger.debug("LEAD >> saveCONTACT >> InsideMethod "+action);
		
			Lead lead = leadService.findLead(new Long(leadId));
			List<AdditionalContact> contacts = lead.getAdditionalContacts();
			AdditionalContact contact = null;

			if(action.equalsIgnoreCase("save")){
				contact = new AdditionalContact();
			}
			if(action.equalsIgnoreCase("update")){
				contact = contactService.find(new Long(form.getContactId()));
			}
			contact.setFirstName(form.getContactFirstName());
			contact.setMiddleInitial(form.getContactMiddleInitial());
			contact.setLastName(form.getContactLastName());
			contact.setTitle(form.getContactTitle());
			contact.setEmail(form.getContactEmail());
			contact.setWorkPhone(form.getPhoneWork());
			contact.setHomePhone(form.getPhoneHome());
			contact.setMobileNo(form.getPhoneMobile());
			contact.setFax(form.getPhoneFax());
			contact.setLead(lead);

			if(action.equalsIgnoreCase("save")){
				contacts.add(contact);
				contact.setCreatedBy(LoggedUser.getUser(request));
				contact.setCreatedAt(new Date());
				lead.setAdditionalContacts(contacts);
				leadService.update(lead);
			}
			if(action.equalsIgnoreCase("update")){
				contacts.add(contact);
				lead.setAdditionalContacts(contacts);
				leadService.update(lead);
			}
			logger.debug("Contact Id "+contact.getId());
		return JsonModelMap.success().data(contact.getFirstName()+" "+contact.getLastName());
	} 	
	


	// This method in LeadOpp.js file for add and update opportunity in window PopUp
    @RequestMapping(value="saveOpportunity", method=RequestMethod.POST)
	public @ResponseBody
	Map<String, Object> saveOpportunity(@RequestBody LeadOppForm form,@RequestParam(required=true, value="action")String action) 
	{
    	logger.debug("Inside lead opportunity search window controller");
    	Lead lead = new Lead();
    	Opportunity opportunity = new Opportunity();
    	
    	if(action.equalsIgnoreCase("update"))
    	{
    		logger.debug("Lead>>update Opportunity>>"+form.getOpportunityId());
    		opportunity = opportunityService.find(new Long(form.getOpportunityId()));
    		
    	}
    	opportunity.setOpportunityTitle(form.getOpportunityTitle());
    	
    	if(StringUtils.isNotEmpty(form.getDealSize()))
    	opportunity.setDealSize(Integer.parseInt(form.getDealSize()));
    	opportunity.setConfidenceLevel(setupService.findById(form.getOppClosingProbabilityId()));
    	
    	    	
    	//if(StringUtils.isNotEmpty(form.getSalesPersonHiddenName()))
    	opportunity.setSalesPerson(employeeService.find(form.getSalesPersonId()));
    	    	
    	if(StringUtils.isNotEmpty(form.getTargetDate()))
    	opportunity.setForecastClosingDate(DateUtil.stringToDate(form.getTargetDate()));
    	
    	if(StringUtils.isNotEmpty(form.getActualCloseDate()))
    	opportunity.setActualCloseDate(DateUtil.stringToDate(form.getActualCloseDate()));
    	
    	if(StringUtils.isNotEmpty(form.getCreateDate()))
    	opportunity.setCreatedDate(DateUtil.stringToDate(form.getCreateDate()));
    	
    	if(StringUtils.isNotEmpty(form.getOpportunityDiscription()))
    	opportunity.setOpportunityDescription(form.getOpportunityDiscription().getBytes());
    	
    	opportunity.setOpportunityStatus(setupService.findById(form.getStatusId()));
    	opportunity.setStage(setupService.findById(form.getStageId()));
    	    	
    	logger.debug("Lead ID Is------"+form.getOppLeadId());
    	if(StringUtils.isNotEmpty(form.getOppLeadId()))
        opportunity.setRelatedContact(leadService.findLead(new Long(form.getOppLeadId())));
    	
  
    	if(action.equalsIgnoreCase("save")){
			opportunityService.create(opportunity);
			}
    	
		if(action.equalsIgnoreCase("update")){
			opportunityService.update(opportunity);
			}

    	return JsonModelMap.success().data(opportunity.getId());
    	}
    
    @RequestMapping(method=RequestMethod.POST, value="activateLead")
    public @ResponseBody 
    Map<String, Object> activateLead(@RequestParam(value="leadId")Long leadId,
    								 @RequestParam(value="doActivate")Boolean doActivate){
    	Lead lead = null;
    	if(leadId != null){
    		lead = leadService.findLead(leadId);
        	if(doActivate == true){
        		lead.setActiveStatus(ActiveQualifier.Active);
        	}
        	if(doActivate == false){
        		lead.setActiveStatus(ActiveQualifier.Inactive);
        	}
        	leadService.update(lead);
        	return JsonModelMap.success();
    	}else{
    		return JsonModelMap.failWithMessage("Failure");
    	}
    }
    
    @RequestMapping(method=RequestMethod.GET, value="leadStatusTypes")
    public @ResponseBody Map<String, Object> leadStatusTypes(){
    	return JsonModelMap.success().data(qualifierService.getLeadStatusTypes());
    } 
    
    @RequestMapping(value ="/leadReqCombo" )
	public @ResponseBody
	Map<String ,Object> issueCombo(@RequestParam(value ="operation") String operation,HttpServletResponse response)
	{
		List<SetupsValue> result = null;
		if(operation.equalsIgnoreCase("industryTypes"))
			result  = setupService.listSetupValue(SetupsModuleQualifier.Lead.ordinal(),SetupsAttributeQualifier.IndustryType.ordinal());
		if(operation.equalsIgnoreCase("sourceTypes"))
			result = setupService.listSetupValue(SetupsModuleQualifier.Lead.ordinal(), SetupsAttributeQualifier.Source.ordinal());
		if(operation.equalsIgnoreCase("categoryTypes"))
			result = setupService.listSetupValue(SetupsModuleQualifier.Lead.ordinal(), SetupsAttributeQualifier.Category.ordinal());
		if(operation.equalsIgnoreCase("gradeTypes"))
			result  = setupService.listSetupValue(SetupsModuleQualifier.Lead.ordinal(),SetupsAttributeQualifier.Grade.ordinal());
		if(operation.equalsIgnoreCase("stageTypes"))
			result = setupService.listSetupValue(SetupsModuleQualifier.Lead.ordinal(), SetupsAttributeQualifier.Stage.ordinal());
		if(operation.equalsIgnoreCase("actionTypes"))
			result = setupService.listSetupValue(SetupsModuleQualifier.Lead.ordinal(), SetupsAttributeQualifier.Action.ordinal());
		if(operation.equalsIgnoreCase("closingProbabilityTypes"))
			result = setupService.listSetupValue(SetupsModuleQualifier.Lead.ordinal(), SetupsAttributeQualifier.Probability.ordinal());
		return JsonModelMap.success().data(result);
	}
    
    
    @RequestMapping(method=RequestMethod.GET, value="countries")
    public @ResponseBody Map<String, Object> countryList(){
    	return JsonModelMap.success().data(leadService.getDummyCountries());
    }    
    
    @RequestMapping(method=RequestMethod.GET, value="provinces")
    public @ResponseBody Map<String, Object> provinceList(){
    	return JsonModelMap.success().data(leadService.getDummyProvinces());
    }    
    
    @RequestMapping(method=RequestMethod.GET, value="owners")
    public @ResponseBody Map<String, Object> ownerList(){
    	return JsonModelMap.success().data(employeeService.findAllEmployeeName());
    }
    
	@RequestMapping(method = RequestMethod.GET, value = "leadSearchCriteriaTypes")
	public @ResponseBody
	Map<String, Object> leadSearchCriteriaList() {
		return JsonModelMap.success().data(leadService.getLeadSearchCriteriaTypes());
	}
	
  	@RequestMapping(method=RequestMethod.GET,value="documentTypes")
  	public @ResponseBody
  	Map<String, Object>documentTypes(){
  		  return JsonModelMap.success().data(qualifierService.getDocumentTypes());
  	} 	
}
